package com.jiedeng.controller.index;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jiedeng.model.*;
import com.jiedeng.util.*;
import com.jiedeng.util.httpclient.HttpClientHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页
 *
 * @author zhouyb
 */
@Controller
@Scope("prototype")
@RequestMapping("/homepage")
public class HomepageController {
    @Value("${config.http.client.url}")
    public String url;
    @Value("${config.prefix}")
    public String downUrl;
    @Value("${config.winReporterPath}")
    private String winPath;
    @Value("${config.linuxReporterPath}")
    private String linuxPath;

    /**
     * 首页工程统计
     *
     * @param page
     * @param pageSize
     * @param epsId
     * @param model
     * @param projectName
     * @param status
     * @param request
     * @return
     */
    @RequestMapping(value = "/findProjectCountByEpsId", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String findProjectCountByEpsId(@RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize, String epsId, Model model, String projectName, String status, HttpServletRequest request) {
        try {
            model.addAttribute("ctx", request.getContextPath());
            Map map = new HashMap();
            map.put("epsId", epsId);
            map.put("projectName", projectName);
            map.put("status", status);
            map.put("personId", SessionUtil.getUserIdSession());
            map.put("page", page);
            map.put("pageSize", pageSize);
            String ret = HttpClientHelper.postRequest2(url + "/homepage/findProjectCountList", map, "utf-8", "");
            String ret2 = HttpClientHelper.postRequest2(url + "/homepage/findProjectCountNum", map, "utf-8", "");
            List<ProjectCount> projectCountList = new ArrayList<>();
            if (ret != null) {
                projectCountList = JSON.parseObject(ret.trim(), new TypeReference<List<ProjectCount>>() {
                });
            }
            int count = Integer.parseInt(ret2);
            model.addAttribute("count", count);
            model.addAttribute("maxPage", count / 10);
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + projectCountList.size());
            model.addAttribute("projectCountList", projectCountList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "homeList";
    }

    /**
     * 获取消息通知
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("findMessage")
    public List<SysMessage> findMessageByPersonId() {
        Person person = (Person) SessionUtil.getUserSession();
        String ret = HttpClientHelper.doGet(url + "/message/findbyperson?personId=" + person.getId());
        List<SysMessage> sysMessageList = JSON.parseObject(ret.trim(), new TypeReference<List<SysMessage>>() {
        });
        return sysMessageList;
    }

    /**
     * 跳转消息页面
     *
     * @param model
     * @param messageId
     * @param request
     * @return
     */
    @RequestMapping("findMessageDetailsUI")
    public String findMessageDetailsUI(Model model, String messageId, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());

        String ret = HttpClientHelper.doGet(url + "/message/findMessageDetailsById?messageId=" + messageId);
        SysMessage sysMessage = JSON.parseObject(ret.trim(), new TypeReference<SysMessage>() {
        });
        //用户
        model.addAttribute("personName", SessionUtil.getUserNameSession());
        //单位
        model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
        model.addAttribute("sysMessage", sysMessage);
        return "home/messageDetails";
    }

    /**
     * 首页点击工程详情
     *
     * @param model
     * @param projectId
     * @param request
     * @return
     */
    @RequestMapping(value = "/findProjectDetails", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String findProjectDetails(Model model, String projectId, HttpServletRequest request) {
        model.addAttribute("ctx", request.getContextPath());
        try {
            //用户
            model.addAttribute("personName", SessionUtil.getUserNameSession());
            //单位
            model.addAttribute("corpName", SessionUtil.getUserCorpNameSession());
            model.addAttribute("projectId", projectId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "home/projectDetails";
    }

    /**
     * 工程详情
     *
     * @param model
     * @param projectId
     * @param request
     * @return
     */
    @RequestMapping(value = "/getProjectDetails", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String getProjectDetails(Model model, String projectId, HttpServletRequest request) {
        try {
            model.addAttribute("ctx", request.getContextPath());
            Map map = new HashMap();
            map.put("projectId", projectId);
            String ret = HttpClientHelper.postRequest2(url + "/homepage/findProjectDetails", map, "utf-8", "");
            if (ret != null) {
                ProjectDetails project = JSON.parseObject(ret.trim(), new TypeReference<ProjectDetails>() {
                });
                model.addAttribute("projectDetails", project);
            }
            model.addAttribute("dataUrl", url);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "home/details";
    }

    /**
     * 照片下载列表
     *
     * @param page
     * @param pageSize
     * @param projectId
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/getphotoListDetails", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String getphotoListDetails(@RequestParam(defaultValue = "1") String page, @RequestParam(defaultValue = "10") String pageSize, String projectId, Model model, HttpServletRequest request) {
        try {
            model.addAttribute("ctx", request.getContextPath());
            Map map = new HashMap();
            map.put("projectId", projectId);
            map.put("page", page);
            map.put("pageSize", pageSize);
            String ret = HttpClientHelper.postRequest2(url + "/homepage/findtaskCountList", map, "utf-8", "");
            String ret2 = HttpClientHelper.postRequest2(url + "/homepage/findtaskCountNum", map, "utf-8", "");
            List<Task> taskArrayList = new ArrayList<>();
            if (ret != null) {
                taskArrayList = JSON.parseObject(ret.trim(), new TypeReference<List<Task>>() {
                });
            }
            int count = Integer.parseInt(ret2);
            model.addAttribute("projectId", projectId);
            //路径
            model.addAttribute("downUrl", downUrl);
            model.addAttribute("count", count);
            model.addAttribute("maxPage", count / 10);
            model.addAttribute("page", page);
            model.addAttribute("pageSize", pageSize);
            //model.addAttribute("query", query);
            model.addAttribute("nowBegin", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + 1);
            model.addAttribute("nowEnd", Integer.parseInt(pageSize) * (Integer.parseInt(page) - 1) + taskArrayList.size());
            model.addAttribute("taskArrayList", taskArrayList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "home/photoList";
    }

    /**
     * 批量下载
     *
     * @return
     */
//    @RequestMapping("fileDownZip")
    @RequestMapping(value = "/fileDownZip", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String fileDownZip(String projectId, String taskId, Model model, HttpServletRequest request, String colseDo) {
        //需要打包的目录    下载文件并获取目录
        String path = "";
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {
            path = winPath;
        } else {
            path = linuxPath;
        }
        try {
            model.addAttribute("ctx", request.getContextPath());
            Map map = new HashMap();
            map.put("projectId", projectId);
            map.put("taskId", taskId);
            map.put("closeDo", colseDo);
            String ret = HttpClientHelper.postRequest2(url + "/homepage/findphotoCountList", map, "utf-8", "");
            List<FileRecord> fileRecordArrayList = new ArrayList<>();
            if (ret != null) {
                fileRecordArrayList = JSON.parseObject(ret.trim(), new TypeReference<List<FileRecord>>() {
                });
                if (fileRecordArrayList != null && fileRecordArrayList.size() > 0) {
                    String sourceFilePath = HttpClientDownReport.getReportFromToFR(downUrl, path, fileRecordArrayList);
                    //String sourceFilePath = "D:/app/uploads/center/reportFrom/dowZip";
                    //String zipFilePath = "D:/app/uploads/center/reportFrom";
                    String zipFilePath = sourceFilePath;
                    String fileName = DatetimeUtil.getDateyyyyMMddhhmmss();
                    boolean flag = ZipUtil.fileToZip(sourceFilePath, zipFilePath, fileName);
//        String path = null;
                    if (flag) {
                        System.out.println("文件打包成功!");
                        List<String> fileSuffix = new ArrayList<String>();
                        fileSuffix.add("xls");
                        fileSuffix.add("xlsx");
                        //打包完成删除多余文件
                        HttpClientDownReport.deleteDirectory(sourceFilePath, fileSuffix);
                        path = zipFilePath + "/" + fileName + ".zip";
                    } else {
                        System.out.println("文件打包失败!");
                    }
                    //重定向至下载文件
                    return ForwardConstants.REDIRECT + "/" + ForwardConstants.COMMON + "/downloadfile?path=" + path;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ForwardConstants.REDIRECT + "/homepage/getphotoListDetails?projectId=" + projectId;
    }

    @RequestMapping("messageJumpUI")
    public String messageJumpUI(String taskId,String infotitle) {
        //projectId#1*taskId#12000015246384051747d0cecaa73d44490a3e017ddf72cea01
        String url=jumpUrl(infotitle,taskId);
        return ForwardConstants.REDIRECT +"/taskManage/taskManageUI?type=2&url="+ url;
    }

    public String jumpUrl(String messageTitle,String taskId) {
        if (ForwardConstants.TASK_PUB.equals(messageTitle)) {
            return "/taskManage/checkItem?taskId="+taskId+"&taskType=1";
        }
        if (ForwardConstants.TASK_REFORM.equals(messageTitle)) {
            return "/taskManage/checkItem?taskId="+taskId+"&taskType=2";
        }
        if (ForwardConstants.TASK_REFORMED.equals(messageTitle)) {
            return "/taskManage/checkItem?taskId="+taskId+"&taskType=3";
        }
        if (ForwardConstants.TASK_REJECT.equals(messageTitle)) {
            return "/taskManage/checkItem?taskId="+taskId+"&taskType=2";
        }
        return "/taskManage/inspectTask?1=1&taskType=1";
    }
}
